package com.example.module_motocircle.adpater

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.lib_net.ApiException
import com.example.lib_net.ResponseEmptyException
import com.example.module_motocircle.api.MotocircleApi
import com.example.module_motocircle.model.PostItem


/**
 *@author Wcj
 *@description
 *@date 2022/7/12 13:36
 */
class PostPageSource(
    private val api: MotocircleApi,
    private val ifFocus: Int? = null,
    private val keyword: String? = null,
    private val memberId: String? = null,
    private val sortType: String? = null,
    private val topicId: String? = null
) : PagingSource<Int, PostItem>() {
    override fun getRefreshKey(state: PagingState<Int, PostItem>): Int? {
        return 1
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PostItem> {
        val currentPage = params.key ?: 1
        val pageSize = params.loadSize
        return try {
            val post = api.getPostData(
                sortType,
                topicId,
                memberId,
                ifFocus,
                currentPage,
                pageSize,
                keyword
            )
            if (post.data == null) {
                return LoadResult.Error(ApiException.getApiException(post.code, post.msg))
            }
            val prevKey: Int? = null
            val nextKey: Int? = if (currentPage == 1) {
                if (post.data!!.pages!! <= 1) {
                    null
                } else {
                    10 / 10 + 1
                }
            } else {
                if (post.data!!.pages!! <= post.data!!.current!!) null else currentPage + 1
            }
            if (!post.data?.records.isNullOrEmpty()) {
                LoadResult.Page(
                    data = post.data.records ?: listOf(),
                    prevKey = prevKey,
                    nextKey = nextKey
                )
            } else {
                //没有数据的情况
                LoadResult.Error(ResponseEmptyException())
            }

        } catch (e: Exception) {
            e.printStackTrace()
            LoadResult.Error(ApiException.getApiException(e))
        }
    }
}